<template>
  <div class="execution-logger h-full flex flex-col bg-gray-50">
    <!-- 主日志区域 -->
    <div class="flex-1 bg-white border border-gray-200 rounded-lg m-4">
      <!-- 日志头部信息 -->
      <div class="p-6 border-b border-gray-200">
        <div class="flex items-center justify-between mb-4">
          <div class="flex items-center">
            <!-- 日志图标 -->
            <div class="w-12 h-12 rounded-full bg-blue-500 text-white flex items-center justify-center text-xl font-bold mr-4">
              <el-icon><iEpDocument /></el-icon>
            </div>
            <div>
              <h2 class="text-xl font-semibold text-gray-800 mb-1">执行日志</h2>
              <p class="text-sm text-gray-500">实时显示脚本执行过程和状态信息</p>
            </div>
          </div>
          
          <!-- 日志控制选项: 日志级别, 清空日志, 导出日志 -->
          <div class="flex items-center space-x-4">
            <div class="flex items-center">
              <span class="text-sm text-gray-500 mr-2">日志级别:</span>
              <el-select v-model="logLevel" size="default" class="w-32">
                <el-option label="全部" value="all" />
                <el-option label="错误" value="error" />
                <el-option label="警告" value="warn" />
                <el-option label="信息" value="info" />
                <el-option label="调试" value="debug" />
              </el-select>
            </div>
            
            <div class="flex items-center space-x-2">
              <el-button type="primary" size="default" @click="clearLogs">
                <el-icon class="mr-1"><iEpDelete /></el-icon>
                清空日志
              </el-button>
              <el-button type="success" size="default" @click="exportLogs">
                <el-icon class="mr-1"><iEpDownload /></el-icon>
                导出日志
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 日志内容区域 -->
      <div class="p-6">
        <div 
          ref="logContainer" 
          class="log-content bg-gray-900 text-green-400 p-4 rounded-lg font-mono text-sm h-96 overflow-auto"
        >
          <div v-if="filteredLogs.length === 0" class="text-gray-500 text-center py-12">
            <div class="w-16 h-16 mx-auto mb-4 bg-gray-700 rounded-full flex items-center justify-center">
              <el-icon class="text-2xl text-gray-400"><iEpDocument /></el-icon>
            </div>
            <h3 class="text-lg font-semibold mb-2">暂无日志信息</h3>
            <p class="text-sm">执行脚本时将显示详细日志</p>
          </div>
          
          <div v-else class="space-y-1">
            <div 
              v-for="(log, index) in filteredLogs" 
              :key="index"
              class="log-entry p-3 rounded-lg transition-all duration-200 hover:bg-gray-800"
              :class="getLogClass(log.level)"
            >
              <div class="flex items-start">
                <div class="flex-shrink-0 mr-3">
                  <div class="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold"
                       :class="getLogLevelBgClass(log.level)">
                    {{ getLogLevelIcon(log.level) }}
                  </div>
                </div>
                <div class="flex-1 min-w-0">
                  <div class="flex items-center justify-between mb-1">
                    <span class="text-xs text-gray-500 font-medium">{{ formatTime(log.timestamp) }}</span>
                    <el-tag 
                      :type="getLogLevelTagType(log.level)" 
                      size="small"
                      class="ml-2"
                    >
                      {{ log.level.toUpperCase() }}
                    </el-tag>
                  </div>
                  <div class="text-sm leading-relaxed">{{ log.message }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部状态栏 -->
      <div class="p-6 border-t border-gray-200 bg-gray-50 flex justify-between items-center">
        <div class="flex items-center space-x-4">
          <span class="text-sm text-gray-600">
            日志条数: <span class="font-semibold text-blue-600">{{ filteredLogs.length }}</span> / {{ logs.length }}
          </span>
          <span v-if="executionStore.isRunning" class="text-sm text-green-600 flex items-center">
            <el-icon class="mr-1 animate-spin"><iEpLoading /></el-icon>
            正在执行...
          </span>
        </div>
        
        <div class="flex items-center space-x-2">
          <el-button size="small" @click="scrollToTop">
            <el-icon class="mr-1"><iEpArrowUp /></el-icon>
            顶部
          </el-button>
          <el-button size="small" @click="scrollToBottom">
            <el-icon class="mr-1"><iEpArrowDown /></el-icon>
            底部
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, watch } from 'vue'
import { useExecutionStore } from '../stores/execution'
import { 
  Delete as iEpDelete,
  Download as iEpDownload,
  Document as iEpDocument,
  Loading as iEpLoading,
  ArrowUp as iEpArrowUp,
  ArrowDown as iEpArrowDown
} from '@element-plus/icons-vue'

const executionStore = useExecutionStore()
const logContainer = ref(null)

// 响应式数据
const logLevel = ref('all')

// 模拟日志数据（将来替换为真实的执行日志）
const logs = ref([
  {
    timestamp: new Date(),
    level: 'info',
    message: '执行日志面板已初始化'
  },
  {
    timestamp: new Date(),
    level: 'info', 
    message: '等待执行命令...'
  }
])

// 计算属性
const filteredLogs = computed(() => {
  if (logLevel.value === 'all') {
    return logs.value
  }
  return logs.value.filter(log => log.level === logLevel.value)
})

// 监听日志变化，自动滚动
watch(() => logs.value.length, () => {
  nextTick(() => {
    if (logContainer.value) {
      logContainer.value.scrollTop = logContainer.value.scrollHeight
    }
  })
})

// 方法
const getLogClass = (level) => {
  const classes = {
    'error': 'text-red-400',
    'warn': 'text-yellow-400', 
    'info': 'text-blue-400',
    'success': 'text-green-400',
    'debug': 'text-gray-400'
  }
  return classes[level] || 'text-white'
}

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const addLog = (level, message) => {
  logs.value.push({
    timestamp: new Date(),
    level,
    message
  })
}

const clearLogs = () => {
  logs.value = []
}

const exportLogs = () => {
  const logText = filteredLogs.value.map(log => 
    `[${formatTime(log.timestamp)}] [${log.level.toUpperCase()}] ${log.message}`
  ).join('\n')
  
  const blob = new Blob([logText], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `execution-log-${Date.now()}.txt`
  a.click()
  URL.revokeObjectURL(url)
}


const scrollToTop = () => {
  if (logContainer.value) {
    logContainer.value.scrollTop = 0
  }
}

const scrollToBottom = () => {
  if (logContainer.value) {
    logContainer.value.scrollTop = logContainer.value.scrollHeight
  }
}

const getLogLevelIcon = (level) => {
  const icons = {
    'error': '!',
    'warn': '[警告]',
    'info': 'i',
    'success': '✓',
    'debug': '?'
  }
  return icons[level] || '•'
}

const getLogLevelBgClass = (level) => {
  const classes = {
    'error': 'bg-red-500 text-white',
    'warn': 'bg-yellow-500 text-white',
    'info': 'bg-blue-500 text-white',
    'success': 'bg-green-500 text-white',
    'debug': 'bg-gray-500 text-white'
  }
  return classes[level] || 'bg-gray-500 text-white'
}

const getLogLevelTagType = (level) => {
  const types = {
    'error': 'danger',
    'warn': 'warning',
    'info': 'info',
    'success': 'success',
    'debug': 'info'
  }
  return types[level] || 'info'
}

// 暴露方法供父组件调用
defineExpose({
  addLog,
  clearLogs
})
</script>

<style scoped>
.execution-logger {
  font-family: 'Inter', 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

/* 日志内容区域样式 */
.log-content {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Courier New', monospace;
  line-height: 1.6;
}

.log-entry {
  border-left: 3px solid transparent;
  transition: all 0.2s ease;
}

.log-entry:hover {
  border-left-color: #3b82f6;
  background: rgba(59, 130, 246, 0.05);
}

/* 日志级别样式 */
.log-entry.error {
  border-left-color: #ef4444;
}

.log-entry.warn {
  border-left-color: #f59e0b;
}

.log-entry.info {
  border-left-color: #3b82f6;
}

.log-entry.success {
  border-left-color: #10b981;
}

.log-entry.debug {
  border-left-color: #6b7280;
}

/* 滚动条样式 */
.log-content::-webkit-scrollbar {
  width: 6px;
}

.log-content::-webkit-scrollbar-track {
  background: #1f2937;
  border-radius: 3px;
}

.log-content::-webkit-scrollbar-thumb {
  background: #4b5563;
  border-radius: 3px;
}

.log-content::-webkit-scrollbar-thumb:hover {
  background: #6b7280;
}

/* 按钮样式增强 */
:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.2s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 选择器样式 */
:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 开关样式 */
:deep(.el-switch) {
  --el-switch-on-color: #3b82f6;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 6px;
  font-weight: 500;
}

/* 空状态样式 */
.log-content .empty-state {
  background: linear-gradient(135deg, #1f2937, #374151);
  border: 2px dashed #4b5563;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .execution-logger .flex.space-x-4 {
    flex-direction: column;
    gap: 1rem;
  }
  
  .execution-logger .flex.justify-between {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
}
</style>
